package com.example.li_han.servlet;

import com.example.li_han.pojo.News;
import com.example.li_han.service.NewsService;
import com.example.li_han.service.NewsTypeService;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@WebServlet(name = "AddNewsServlet", value = "/AddNewsServlet")
public class AddNewsServlet extends HttpServlet {
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=utf-8");

        BufferedReader br = req.getReader();
        StringBuilder sbuffer = new StringBuilder();
        String s;

        while((s = br.readLine()) != null) {
            sbuffer.append(s);
        }

        String requestBody = sbuffer.toString();
        System.out.println("收到添加新闻请求: " + requestBody);

        Map<String, Object> resultMap = new HashMap<>();

        try {
            // 解析JSON数据
            Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
            Map<String, Object> rawData = gson.fromJson(requestBody, mapType);

            if (rawData == null) {
                resultMap.put("code", 500);
                resultMap.put("msg", "请求数据为空");
                sendResponse(resp, resultMap);
                return;
            }

            // 验证必要字段
            if (!rawData.containsKey("typeId") || !rawData.containsKey("newsTitle") || !rawData.containsKey("newsContent")) {
                resultMap.put("code", 500);
                resultMap.put("msg", "缺少必要参数");
                sendResponse(resp, resultMap);
                return;
            }

            // 创建新闻对象
            News news = new News();

            // 设置typeId
            Object typeIdObj = rawData.get("typeId");
            if (typeIdObj instanceof Double) {
                news.setTypeId(((Double) typeIdObj).intValue());
            } else if (typeIdObj instanceof Integer) {
                news.setTypeId((Integer) typeIdObj);
            } else {
                news.setTypeId(Integer.parseInt(typeIdObj.toString()));
            }

            // 设置typeName
            NewsTypeService newsTypeService = new NewsTypeService();
            String typeName = newsTypeService.getAllNewsTypes().stream()
                    .filter(type -> type.getTypeId() == news.getTypeId())
                    .findFirst()
                    .map(com.example.li_han.pojo.NewsType::getTypeName)
                    .orElse("");
            news.setTypeName(typeName);

            news.setNewsTitle(rawData.get("newsTitle").toString());
            news.setNewsContent(rawData.get("newsContent").toString());

            // 设置图片
            if (rawData.containsKey("newsImage") && rawData.get("newsImage") != null) {
                news.setNewsImage(rawData.get("newsImage").toString());
            }

            // 设置布尔字段
            if (rawData.containsKey("isTop") && rawData.get("isTop") != null) {
                news.setTop(Boolean.parseBoolean(rawData.get("isTop").toString()));
            }

            if (rawData.containsKey("isShowHome") && rawData.get("isShowHome") != null) {
                news.setShowHome(Boolean.parseBoolean(rawData.get("isShowHome").toString()));
            }

            if (rawData.containsKey("isImageNews") && rawData.get("isImageNews") != null) {
                news.setImageNews(Boolean.parseBoolean(rawData.get("isImageNews").toString()));
            }

            // 设置viewCount
            if (rawData.containsKey("viewCount") && rawData.get("viewCount") != null) {
                Object viewCountObj = rawData.get("viewCount");
                if (viewCountObj instanceof Double) {
                    news.setViewCount(((Double) viewCountObj).intValue());
                } else if (viewCountObj instanceof Integer) {
                    news.setViewCount((Integer) viewCountObj);
                } else {
                    news.setViewCount(Integer.parseInt(viewCountObj.toString()));
                }
            } else {
                news.setViewCount(0);
            }

            // 设置发布日期
            if (rawData.containsKey("publishDate") && rawData.get("publishDate") != null) {
                String publishDateStr = rawData.get("publishDate").toString().trim();
                if (!publishDateStr.isEmpty()) {
                    try {
                        // 解析日期字符串 (格式: yyyy-MM-dd)
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                        Date publishDate = dateFormat.parse(publishDateStr);
                        news.setPublishDate(new java.sql.Date(publishDate.getTime()));
                        System.out.println("设置发布日期: " + publishDateStr);
                    } catch (ParseException e) {
                        // 日期解析失败，使用当前日期
                        news.setPublishDate(new java.sql.Date(System.currentTimeMillis()));
                        System.out.println("日期格式错误，使用当前日期作为发布日期");
                    }
                } else {
                    // 日期字符串为空，使用当前日期
                    news.setPublishDate(new java.sql.Date(System.currentTimeMillis()));
                    System.out.println("发布日期为空，使用当前日期");
                }
            } else {
                // 没有提供发布日期，使用当前日期
                news.setPublishDate(new java.sql.Date(System.currentTimeMillis()));
                System.out.println("未提供发布日期，使用当前日期");
            }

            // 添加新闻
            NewsService newsService = new NewsService();
            int result = newsService.addNews(news);

            if (result > 0) {
                resultMap.put("code", 200);
                resultMap.put("msg", "添加新闻成功");
                resultMap.put("newsId", result);
            } else {
                resultMap.put("code", 500);
                resultMap.put("msg", "添加新闻失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", 500);
            resultMap.put("msg", "服务器异常: " + e.getMessage());
        }

        sendResponse(resp, resultMap);
    }

    private void sendResponse(HttpServletResponse resp, Map<String, Object> resultMap) throws IOException {
        String json = gson.toJson(resultMap);
        resp.getWriter().write(json);
    }
}